import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { ListItemType } from '../../types'

// 为 slice state 定义一个类型
interface ShopCarState {
  ShopCarList: ShopCarItemType[]
  totalCount:number
}

interface ShopCarItemType extends ListItemType {
  count: number,
  checked: boolean
}

// 使用该类型定义初始 state
const initialState: ShopCarState = {
  ShopCarList: [],
  totalCount:0
}

export const ShopCarSlice = createSlice({
  name: 'shopcar',
  // `createSlice` 将从 `initialState` 参数推断 state 类型
  initialState,

  reducers: {
    // 使用 PayloadAction 类型声明 `action.payload` 的内容
    addShopCar: (state, action: PayloadAction<ListItemType>) => {
      const product = state.ShopCarList.find(v => v.id === action.payload.id)
      // 如果购物车中存在该商品， 使其数量+1
      if (product) {
        product.count++
      } else {
        // 商品在购物车中不存在，将该商品添加入购物车，要加上count:1 和 checked:false属性
        const newItem = { ...action.payload, count: 1, checked: false }
        state.ShopCarList.push(newItem)
      }
    },
    // 点击+，数量增加
    increaseCount: (state, action: PayloadAction<string>) => {
      const item = state.ShopCarList.find(v => v.id === action.payload)
      if (item) {
        item.count++
      }
    },
    // 点击-，数量减少
    decreaseCount: (state, action: PayloadAction<string>) => {
      const item = state.ShopCarList.find(v => v.id === action.payload)
      if (item) {
        item.count--
        if (item.count <= 0) {
          state.ShopCarList = state.ShopCarList.filter(v => v.id !== item.id)
        }
      }
    },
    switchCarCheck: (state, action: PayloadAction<string>) => {
      const item = state.ShopCarList.find(v => v.id === action.payload)
      if (item) {
        item.checked = !item.checked
      }
    },
    // 全选
    allChecked:(state, action: PayloadAction<boolean>) => {
      state.ShopCarList.forEach(v => v.checked=action.payload)
    },
  }
})

export const { addShopCar, increaseCount, decreaseCount, switchCarCheck,allChecked } = ShopCarSlice.actions


export default ShopCarSlice.reducer